<template>
	<view class="form-container">
		<!-- 表单主体 -->
		<scroll-view scroll-y class="form-body">
			<!-- 住院号 -->
			<view class="form-card">
			  <text class="form-label required">您的住院号</text>
			  <view class="hospital-number-display">
			    {{ form.hospitalNumber }}
			  </view>
			  <view class="divider"></view>
			</view>

			<!-- 性别固定 -->
			<view class="form-card">
				<text class="form-label required">您的性别</text>
				<view class="phone-input">
					<view>{{ form.gender }}</view>
				</view>
				<view class="divider"></view>
			</view>

			<!-- 年龄固定 -->
			<view class="form-card">
				<text class="form-label required">您的年龄</text>
				<view class="phone-input">
					<view>{{ form.age }}</view>
				</view>
				<view class="divider"></view>
			</view>
			
			<!-- 造口类型 -->
			<FormPicker label="造口类型" v-model="form.stomaType" :options="stomaTypes" placeholder="请选择造口类型"
				:required="true" />
			<!-- 具体造口类型输入框，当选择"其他"时显示 -->
			<FormInput 
				label="具体造口类型" 
				v-model="stomaTypeOther" 
				placeholder="请输入具体造口类型" 
				:required="form.stomaType === '其他'" 
				v-if="form.stomaType === '其他'" 
			/>
				
			<MultiDatePicker label="手术日期" v-model="form.surgeryDate" placeholder="请选择手术日期" :required="true" />

			<!-- 原发病 -->
			<FormInput label="原发病(参考出院记录)" v-model="form.primaryDisease" placeholder="请输入原发病名称" :required="true" />

			<!-- 通信地址（带自动定位） -->
			<view class="form-card">
				<text class="form-label required">通信地址</text>
				<view class="address-container">
					<picker mode="region" @change="(e) => form.address = e.detail.value">
						<view class="picker-item">
							<text>{{ form.address.length ? form.address.join(' ') : '自动获取省市信息' }}</text>
						</view>
					</picker>
					<input v-model="form.detailAddress" placeholder="详细地址（街道门牌）" placeholder-class="placeholder-style"
						class="detail-input" />
				</view>
				<view class="divider"></view>
			</view>

			<!-- 手机号码 -->
			<FormInput label="手机号" v-model="form.phone" placeholder="请输入手机号" type="number" />

			<!-- 造口导管 -->
			<RadioGroup label="造口导管类型(请参考下列示例的造口导管)" v-model="form.hasCatheter" :options="[
				     { label: '有',type:'text', value: '有' },
				     { label: '无',type:'text', value: '无' }
				   ]" :required="true" :showDivider="false" :haveExample="true" :images="catherImages" />
		   <ImageUploader label="具体造口导管图片" v-model="form.catheterType" v-if="form.hasCatheter==='有'" :required="true" />
			<RadioGroup label="导管有无移位(请参考下列示例的导管移位)" v-model="form.move" :options="[
				      { label: '有',type:'text', value: '有' },
				      { label: '无',type:'text', value: '无' }
				    ]" :required="true" :showDivider="false" haveExample="true" :images="moveImages"
					 v-if="form.hasCatheter !== '无' && form.hasCatheter !== ''"/>
			<ImageUploader label="具体导管移位图片" v-model="form.moveType" v-if="form.move==='有'" :required="true" />
			<RadioGroup label="导管有无堵塞" v-model="form.hasBlock" :options="[
				       { label: '有',type:'text', value: true },
				       { label: '无',type:'text', value: false }
				     ]" :required="true" :showDivider="false" v-if="form.hasCatheter !=='无' && form.hasCatheter !== ''"/>
			<RadioGroup label="导管有无定期更换" v-model="form.hasChange" :options="[
				        { label: '有',type:'text', value: true },
				        { label: '无',type:'text', value: false }
				      ]" :required="true" :showDivider="false" v-if="form.hasCatheter !=='无' && form.hasCatheter !== ''"/>
			<FormInput label="定期更换时间" v-model="form.changeCatheterTime" placeholder="请输入更换时间" v-if="form.hasChange" :required="true" />
			<FormInput label="导管备注" v-model="form.remarks" placeholder="请输入备注" type="string" v-if="form.hasCatheter !=='无' && form.hasCatheter !== ''"/>

			<RadioGroup label="造口周围有无皮炎(请参考下面给出的发炎示例)" v-model="form.hasDermatitis" :options="[
				     { label: '有',type:'text', value: true },
				     { label: '无',type:'text', value: false }
				   ]" :required="true" :showDivider="false" :haveExample="true" :images="dermatitisImages"/>
			<ImageUploader
			      label="具体皮炎图片" 
			      v-model="form.dermatitisPic"
				  v-if="form.hasDermatitis"
				   :required="true"
			    />
		   <FormPicker label="皮炎范围" v-model="form.range" :options="ranges" placeholder="请选择皮炎范围"
			:required="true" v-if="form.hasDermatitis"/>
			<!-- 具体皮炎范围输入框，当选择"其它"时显示 -->
			<FormInput 
				label="具体皮炎范围" 
				v-model="rangeOther" 
				placeholder="请输入具体皮炎范围" 
				:required="form.range === '其它'" 
				v-if="form.hasDermatitis && form.range === '其它'" 
			/>
			<FormPicker label="皮炎位置" v-model="form.position" :options="positions" placeholder="请选择皮炎位置"
						:required="true" v-if="form.hasDermatitis"/>
			<RadioGroup label="造口周围皮肤有无破损" v-model="form.hasDamage" :options="[
				     { label: '有',type:'text', value: true },
				     { label: '无',type:'text', value: false }
				   ]" :required="true" :showDivider="false"/>
			<RadioGroup label="泌尿系统有无感染" v-model="form.hasInfection" :options="[
				     { label: '有',type:'text', value: true },
				     { label: '无',type:'text', value: false }
				   ]" :required="true" :showDivider="false" />
			<RadioGroup label="有无发热情况" v-model="form.hasFever" :options="[
				     { label: '有',type:'text', value: true },
				     { label: '无',type:'text', value: false }
				   ]" :required="true" :showDivider="false" />
			<RadioGroup label="有无腰疼情况" v-model="form.hasbackPain" :options="[
				     { label: '有',type:'text', value: true },
				     { label: '无',type:'text', value: false }
				   ]" :required="true" :showDivider="false" />
			<RadioGroup label="有无尿液浑浊情况" v-model="form.hasmuddy" :options="[
				     { label: '有',type:'text', value: true },
				     { label: '无',type:'text', value: false }
				   ]" :required="true" :showDivider="false" />
			<FormPicker label="运动方式" v-model="form.sportsType" :options="sportsTypes" placeholder="请选择运动方式"
				:required="true" />
			<FormInput label="运动方式详细" v-model="form.sportsTypeDetail" placeholder="请输入运动方式详细" :required="true" type="string" v-if="form.sportsType === '其他'"/>
			<FormPicker label="洗浴情况" v-model="form.showerType" :options="showerTypes" placeholder="请选择洗浴方式"
				:required="true" />
			<FormPicker label="饮食情况" v-model="form.foodType" :options="foodTypes" placeholder="请选择饮食情况"
				:required="true" />
			<FormPicker label="饮水量" v-model="form.waterType" :options="waterTypes" placeholder="请选择饮水量"
				:required="true" />
			<FormPicker label="更换方法" v-model="form.changeType" :options="changeTypes" placeholder="请选择更换方法"
				:required="true" />
			<FormPicker label="更换周期(底盘)" v-model="form.changeRoutine" :options="changeRoutines"
				placeholder="请选择更换周期(底盘)" :required="true" />
			<FormPicker label="更换周期(袋子)" v-model="form.changeRoutine1" :options="changeRoutines1"
				placeholder="请选择更换周期(袋子)" :required="true" />
			<FormPicker label="产品获取方式" v-model="form.getMethod" :options="getMethods" placeholder="产品获取方式"
				:required="true" />
			<FormInput label="产品获取方式详细" v-model="form.getMethodDetail" placeholder="请输入产品获取方式详细" :required="true" type="string" v-if="form.getMethod === '其他'"/>
			<FormInput label="建议" v-model="form.remarksEnd" placeholder="请输入建议" type="string" />
			<button class="button" :disabled="submitting" @click="submitForm">
				{{ submitting ? '提交中...' : '提交' }}
			</button>
		</scroll-view>
	</view>
</template>

<script>
	import RadioGroup from '../../components/RadioGroup.vue';
	import FormInput from '../../components/FormInput.vue';
	import FormPicker from '../../components/FormPicker.vue';
	import DatePickerField from '../../components/DatePickerField.vue';
	import config from '../../config.js';
	import MultiDatePicker from '../../components/MultiDatePicker.vue';
	import ImageUploader from '../../components/ImageUploader.vue';
	
	export default {
		components: {
			RadioGroup,
			FormInput,
			FormPicker,
			DatePickerField,
			MultiDatePicker,
			ImageUploader
		},
		data() {
			return {
				submitting: false,
				// 新增两个字段存储"其他"选项的具体内容
				stomaTypeOther: '',  // 具体造口类型
				rangeOther: '',      // 具体皮炎范围
				form: {
					hospitalNumber: uni.getStorageSync('hospitalNumber'),
					gender: uni.getStorageSync("gender"),
					age: uni.getStorageSync("age"),
					stomaType: '',
					surgeryDate: uni.getStorageSync("surgery_date"),
					primaryDisease: uni.getStorageSync("disease"),
					address: uni.getStorageSync("address"),
					detailAddress: uni.getStorageSync("detailAddress"),
					phone: uni.getStorageSync("phone"),
					hasCatheter: '',
					catheterType:'',
					move: '',
					moveType:'',
					hasDermatitis: null,
					dermatitisPic:'',
					hasInfection: null,
					hasFever: null,
					hasbackPain: null,
					hasDamage: null,
					hasBlock: null,
					hasChange: null,
					changeCatheterTime:'',
					hasmuddy: null,
					remarks: '',
					range: '',
					position: '',
					sportsType: '',
					sportsTypeDetail: '',
					showerType: '',
					foodType: '',
					waterType: '',
					changeType: '',
					changeRoutine: '',
					changeRoutine1: '',
					getMethod: '',
					getMethodDetail: '',
					remarksEnd: ''
				},
				stomaTypes: ['结肠造口', '回肠造口', '泌尿造口', '其他'],
				ranges:['2cm*2cm','4cm*4cm','其它'],
				positions:['造口附近','其它位置'],
				sportsTypes: ['慢走', '其他'],
				showerTypes: ['仅擦洗', '洗浴正常频次'],
				foodTypes: ['正常', '流质(如：牛奶、米汤、果汁等)'],
				waterTypes: ['<1000ml', '1000ml-2000ml', '2000ml-3000ml', '>3000ml'],
				changeTypes: ['熟练', '一般', '不熟练'],
				changeRoutines: ['1天', '2天', '3天', '4天', '5天', '6天', '7天'],
				changeRoutines1: ['1天', '2天', '3天', '4天', '5天', '6天', '7天'],
				getMethods: ['医院', '其他'],
				catherImages:['https://lost-andfound.oss-cn-shanghai.aliyuncs.com/picture/DanDaoGuan.jpg',
							'https://lost-andfound.oss-cn-shanghai.aliyuncs.com/picture/ShuangDaoGuan.jpg',
							'https://lost-andfound.oss-cn-shanghai.aliyuncs.com/picture/SanDaoGuan.jpg'],
				moveImages:['https://lost-andfound.oss-cn-shanghai.aliyuncs.com/picture/DaoGuanYiWei.jpg'],
				dermatitisImages:['https://lost-andfound.oss-cn-shanghai.aliyuncs.com/picture/ZaoKouFaYan.jpg']
			}
		},
		created() {
			this.form.hospitalNumber = uni.getStorageSync('hospitalNumber');
		},
		methods: {
			// 表单验证
			validateForm() {
				console.log(this.form)
				const errors = {};
				  const booleanFields = [
				    'hasDermatitis', 'hasInfection', 
				    'hasFever', 'hasbackPain', 'hasDamage', 'hasBlock', 
				    'hasChange', 'hasmuddy'
				  ];
				
				  const requiredFields = {
				    hospitalNumber: '住院号',
				    gender: '性别',
				    age: '年龄',
				    stomaType: '造口类型',
				    surgeryDate: '手术日期',
				    primaryDisease: "原发病",
				    address: "地址",
				    detailAddress: "详细地址",
				    hasCatheter: "有无造口导管",
					
					catheterType:"造口导管类型",
				    move: "导管有无移位",
					moveType:"导管移位类型",
				    hasBlock: "导管有无堵塞",
				    hasChange: "导管有无定期更换",
					changeCatheterTime:"定期更换时间",
					
				    hasDermatitis: "造口周围有无皮炎",
					
					dermatitisPic:"皮炎图片",
				    range: "皮炎范围",
				    position: "皮炎位置",
					
					hasDamage: "造口周围皮肤有无破损",
				    hasInfection: "泌尿系统有无感染",
				    hasFever: "有无发热情况",
				    hasbackPain: "有无腰疼情况",
				    hasmuddy: "有无尿液浑浊情况",
				    sportsType: "运动方式",
					
					sportsTypeDetail: '详细运动方式',
					
				    showerType: "洗浴情况",
				    foodType: "饮食情况",
				    waterType: "饮水量",
				    changeType: "更换方法",
				    changeRoutine: "更换周期(底盘)",
				    changeRoutine1: "更换周期(袋子)",
				    getMethod: "产品获取方式",
					
					getMethodDetail: "详细产品获取方式"
				  };
				
				for (const [field, label] of Object.entries(requiredFields)) {
				    // 处理布尔值字段
				    if (booleanFields.includes(field)) {
						if((field === 'hasBlock' || field === 'hasChange') && (this.form.hasCatheter === '无' || this.form.hasCatheter === '')) {
							continue
						}
						if(field === 'hasDamage' && this.form.hasDermatitis !== true) {
							continue
						}
				      if (this.form[field] !== true && this.form[field] !== false) {
				        errors[field] = `${label}必须选择`;
				      }
				    } 
				    // 处理其他字段
				    else if (!this.form[field]) {
				      // 特殊处理range和position字段 - 只有当hasDermatitis为true时才需要
				      if ((field === 'range' || field === 'position') && this.form.hasDermatitis !== true) {
				        continue;
				      }
					  if(field === 'catheterType' && this.form.hasCatheter !== '有') {
						  continue
					  }
					  if(field === 'move' && this.form.hasCatheter !== '有') {
						  continue
					  }
					  if(field === 'moveType' && this.form.move !== '有') {
						  continue
					  }
					  if(field === 'changeCatheterTime' && this.form.hasChange !== true) {
						  continue
					  }
					  if(field === 'dermatitisPic' && this.form.hasDermatitis !== true) {
						  continue
					  }
					  if(field === 'sportsTypeDetail' && this.form.sportsType !== '其他') {
						  continue
					  }
					  if(field === 'getMethodDetail' && this.form.getMethod !== '其他') {
						  continue
					  }
				      errors[field] = `${label}不能为空`;
				    }
				  }
				
				// 验证"其他"造口类型的具体内容
				if (this.form.stomaType === '其他' && !this.stomaTypeOther) {
					errors.stomaTypeOther = '请输入具体造口类型';
				}
				
				// 验证"其它"皮炎范围的具体内容
				if (this.form.hasDermatitis && this.form.range === '其它' && !this.rangeOther) {
					errors.rangeOther = '请输入具体皮炎范围';
				}
				
				// 手机号验证
				if (this.form.phone && !/^1[3-9]\d{9}$/.test(this.form.phone)) {
					errors.phone = '请输入正确的手机号码';
				}
				
				// 年龄验证
				if (this.form.age && (isNaN(this.form.age) || this.form.age < 0 || this.form.age > 120)) {
					errors.age = '请输入正确的年龄';
				}
				
				this.formErrors = errors;
				console.log(errors)
				return Object.keys(errors).length === 0;
			},
			
			
			// 准备提交数据
			prepareSubmitData() {
				// 处理更换周期，将天数转换为数字
				const chassisCycle = parseInt(this.form.changeRoutine) || 0;
				const bagCycle = parseInt(this.form.changeRoutine1) || 0;
				
				// 确定最终的造口类型（如果是"其他"则使用用户输入的具体值）
				const finalStomaType = this.form.stomaType === '其他' 
					? this.stomaTypeOther 
					: this.form.stomaType;
				
				// 确定最终的皮炎范围（如果是"其它"则使用用户输入的具体值）
				const finalRange = this.form.range === '其它' 
					? this.rangeOther 
					: this.form.range;
				
				return {
					hospitalNumber: this.form.hospitalNumber,
					gender: this.form.gender,
					age: this.form.age,
					stomaType: finalStomaType,  // 使用处理后的造口类型
					surgeryDate: this.form.surgeryDate.filter(str => str !== "").join(" "),
					address: this.form.address.join(' ') + ' ' + this.form.detailAddress,
					phone: this.form.phone,
					stomaCatheter: this.form.hasCatheter === '无' ? '无' : this.form.catheterType,
					catheterDisplacement: this.form.move === '无' ? '无' : this.form.moveType,
					catheterBlockage: this.form.hasBlock ? '有' : '无',
					catheterReplacement: this.form.hasChange ? this.form.changeCatheterTime : '无',
					catheterNotes: this.form.remarks || '',
					peristomalDermatitis: this.form.hasDermatitis ? this.form.dermatitisPic : '无',
					skinDamage: this.form.hasDamage ? '有' : '无',
					dermatitisRange: finalRange,  // 使用处理后的皮炎范围
					dermatitisLocation: this.form.position || '',
					urinaryTractInfection: this.form.hasInfection ? '有' : '无',
					fever: this.form.hasFever ? '有' : '无',
					backPain: this.form.hasbackPain ? '有' : '无',
					backPainNote: '',
					cloudyUrine: this.form.hasmuddy ? '有' : '无',
					cloudyUrineNote: '',
					exercise: this.form.sportsType === '其他' ? this.form.sportsTypeDetail : this.form.sportsType,
					bath: this.form.showerType,
					diet: this.form.foodType,
					drink: this.form.waterType,
					dietDrinkNote: '',
					replaceMethod: this.form.changeType,
					chassisCycle: chassisCycle,
					bagCycle: bagCycle,
					acquisitionMethod: this.form.getMethod === '其他' ? this.form.getMethodDetail : this.form.getMethod,
					note: this.form.remarksEnd || ''
				};
			},
			
			// 提交表单
			async submitForm() {
				if (this.submitting) return;
				
				if (!this.validateForm()) {
					uni.showToast({
						title: '请完善表单信息',
						icon: 'none'
					});
					return;
				}
				
				this.submitting = true;
				try {
					const submitData = this.prepareSubmitData();
					console.log(submitData)
					const response = await new Promise((resolve, reject) => {
					    uni.request({
					        url: `${config.baseUrl}/patient/insertNurseInfo`,
					        method: 'POST',
					        data: submitData,
					        header: {
					          'Content-Type': 'application/json',
					          'Authorization': uni.getStorageSync('token') || ''
					        },
					        success: (res) => resolve(res),
					        fail: (err) => reject(err)
					    });
					});
					
					console.log('Response Status Code:', response.statusCode);
					console.log('Response Data:', response.data);
					    
					
					if (response.statusCode === 200 && response.data && response.data.code === 1) {
						// 重置表单
						this.resetForm();
						uni.switchTab({
						    url: '/pages/main/main'
						});
						uni.setStorageSync('access', '1');
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						});
					} else {
						throw new Error(response.data?.msg || '提交失败');
					}
				} catch (error) {
					console.error('提交表单错误:', error);
					uni.showToast({
						title: error?.message || '提交失败，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.submitting = false;
				}
			},
			
			// 重置表单
			resetForm() {
				this.stomaTypeOther = '';  // 重置其他造口类型输入
				this.rangeOther = '';      // 重置其他皮炎范围输入
				this.form = {
					hospitalNumber: uni.getStorageSync('hospitalNumber'),
					gender: '',
					age: '',
					stomaType: '',
					surgeryDate: '',
					primaryDisease: '',
					address: [],
					detailAddress: '',
					phone: '',
					hasCatheter: null,
					move: null,
					hasDermatitis: null,
					hasInfection: null,
					hasFever: null,
					hasbackPain: null,
					hasDamage: null,
					hasBlock: null,
					hasChange: null,
					hasmuddy: null,
					remarks: '',
					range: '',
					position: '',
					sportsType: '',
					showerType: '',
					foodType: '',
					waterType: '',
					changeType: '',
					changeRoutine: '',
					changeRoutine1: '',
					getMethod: '',
					remarksEnd: ''
				};
				this.formErrors = {};
			}
		},
		watch: {
			'form.hasCatheter'(newVal) {
				if (!newVal) {
					// 清空相关字段
					this.form.move = null;
					this.form.hasBlock = null;
					this.form.hasChange = null;
					this.form.remarks = '';
				}
			},
			'form.hasDermatitis'(newVal) {
				if (!newVal) {
					// 清空相关字段
					this.form.hasDamage = null;
					this.form.range = '';
					this.form.position = '';
					this.rangeOther = '';  // 同时清空具体皮炎范围
				}
			},
			// 当造口类型改变时，如果不是"其他"则清空具体造口类型输入
			'form.stomaType'(newVal) {
				if (newVal !== '其他') {
					this.stomaTypeOther = '';
				}
			},
			// 当皮炎范围改变时，如果不是"其它"则清空具体皮炎范围输入
			'form.range'(newVal) {
				if (newVal !== '其它') {
					this.rangeOther = '';
				}
			}
		}
	}
</script>

<style lang="scss">
	.form-container {
		background-color: #f8f9fa;
		min-height: 100vh;
		padding: 20rpx;

		.header {
			display: flex;
			align-items: center;
			padding: 30rpx 0;

			&-icon {
				width: 48rpx;
				height: 48rpx;
				margin-right: 15rpx;
			}

			&-text {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}
		}

		.form-body {
			height: calc(100vh - 180rpx);
		}

		.form-card {
			background: white;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 24rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);

			.form-label {
				font-size: 32rpx;
				color: #333;
				margin-bottom: 30rpx;
				display: block;

				&.required::before {
					content: '*';
					color: #f44336;
					margin-right: 8rpx;
				}
			}

			.form-input {
				font-size: 30rpx;
				height: 80rpx;
				line-height: 80rpx;
			}

			.divider {
				height: 1rpx;
				background: #eee;
				margin: 20rpx -30rpx 0;
			}
		}
		.picker-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 30rpx;
			color: #666;
			height: 80rpx;
			line-height: 80rpx;

			.arrow-icon {
				width: 24rpx;
				height: 24rpx;
				opacity: 0.5;
			}
		}

		.placeholder-style {
			color: #bbb;
		}
	}
	.address-container {
		.icon-left {
			width: 32rpx;
			height: 32rpx;
			margin-right: 15rpx;
			opacity: 0.7;
		}

		.detail-input {
			margin-top: 20rpx;
			font-size: 28rpx;
			padding: 20rpx 0;
		}
	}

	.phone-input {
		display: flex;
		align-items: center;
		background-color: #f8f9fa;
		height: 60rpx;

		.prefix {
			color: #666;
			margin-right: 20rpx;
			font-size: 30rpx;
		}

		.form-input {
			flex: 1;
		}
	}
	.icon-right {
		width: 24rpx;
		height: 24rpx;
		opacity: 0.5;
	}
	.button{
		border-radius: 8px;
		background-color: #4361ee;
		color: white;
		width: 400rpx;
		margin-top: 50rpx;
	}
	
	.hospital-number-display {
	    font-size: 30rpx;
	    color: #333;
	    padding: 20rpx 0;
	    background: #f8f9fa; /* 可选：背景色与输入框一致 */
	    border-radius: 8rpx;
	}
</style>
